package com.lb.statck.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.lb.statck.common.result.Result;
import com.lb.statck.util.OssUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 @RestController
@RequestMapping("/api/uploadFile")
public class FileUploadController {

    @Value("${ali.oss.BUCKETNAME}")
    private String BUCKETNAME;

    @Value("${ali.oss.ENDPOINT}")
    private String ENDPOINT;

    @Value("${ali.oss.ACCESS_KEY_ID}")
    private String ACCESS_KEY_ID;

    @Value("${ali.oss.ACCESS_KEY_SECRET}")
    private String ACCESS_KEY_SECRET;

    @PostMapping
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            Result result = new Result();
            return result;
        }
        try {
            // 保存文件到阿里云OSS
            String objectName = "uploads/" + file.getOriginalFilename();
            String fileUrl = OssUtil.uploadFile(BUCKETNAME, ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET, objectName, file.getInputStream());
            Result result = new Result();
            result.setData(fileUrl);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            Result result = new Result();
            return result;
        }
    }
}